package servlet;

import dao.NewsDao;
import model.News;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.List;

@WebServlet(urlPatterns = "/NewsPublishServlet.do")
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2,    // 2MB
        maxFileSize = 1024 * 1024 * 10,        // 10MB
        maxRequestSize = 1024 * 1024 * 50)     // 50MB
public class NewsPublishServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            NewsDao newsDao = new NewsDao();
            List<News> newsList = newsDao.getAllNews();
            request.setAttribute("newsList", newsList);
            request.getRequestDispatcher("/admin/news_view.jsp").forward(request, response);
        } catch (SQLException e) {
            throw new ServletException(e);
        }
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uploadPath = getServletContext().getRealPath("") + File.separator + "upload";
        File uploadDir = new File(uploadPath);

        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        String author = request.getParameter("author");
        Part filePart = request.getPart("image");

        String fileName = filePart.getSubmittedFileName();
        String filePath = uploadPath + File.separator + fileName;

        try (InputStream fileContent = filePart.getInputStream();
             FileOutputStream fos = new FileOutputStream(filePath)) {
            int read;
            final byte[] bytes = new byte[1024];
            while ((read = fileContent.read(bytes)) != -1) {
                fos.write(bytes, 0, read);
            }
        }

        try {
            NewsDao newsDao = new NewsDao();
            boolean saveNews = newsDao.saveNews(title, author, content, fileName);

            if (saveNews) {
                response.sendRedirect(request.getContextPath() + "/admin/news_view.jsp");
            } else {
                response.sendRedirect(request.getContextPath() + "/home/404.html");
            }
        } catch (SQLException e) {
            throw new ServletException(e);
        }
    }
}
